package ejemplo.transformacion.xsl.servlets;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

/**
 * Servlet implementation class ControladorPruebasXML
 */
public class ControladorPruebasXML extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String xml="grupoTarea.xml";
		String xsl="grupoTarea.xsl";
		String xsd="grupoTarea.xsd";
		if(request.getParameter("xml")!=null && !request.getParameter("xml").equals("")){
			xml=request.getParameter("xml");
		}
		if(request.getParameter("xsd")!=null && !request.getParameter("xsd").equals("")){
			xsd=request.getParameter("xsd");
		}
		if(request.getParameter("xsl")!=null && !request.getParameter("xsl").equals("")){
			xsl=request.getParameter("xsl");
		}
		try {
			verificaXML_XSD(creaFile(xml), creaFile(xsd));
		} catch (SAXException e1) {
			// TODO Auto-generated catch block
			System.out.println(e1.getMessage());
			throw new ServletException(e1);
		}
		String res;
		try {
			res = transforma(xml, xsl);
			response.getWriter().print(res);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new ServletException(e);
		}

	}

	  public  void verificaXML_XSD(File xmlFile, File xsdFile) throws SAXException, IOException {
		    	Source xml=new StreamSource(xmlFile);
		    	Source xsd=new StreamSource(xsdFile);
		    	
		      // define the type of schema - we use W3C:
		      String schemaLang = "http://www.w3.org/2001/XMLSchema";

		      // get validation driver:
		      SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

			// create schema by reading it from an XSD file: new StreamSource("sample.xsd")
		      Schema schema = factory.newSchema(xsd);
		      Validator validator = schema.newValidator();

		      // at last perform validation:
		      validator.validate(xml);

		  }

	private String transforma(String xml, String xsl)
			throws TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException {
		File fileXMLOrigen = creaFile(xml);
		File fileXSLOrigen = creaFile(xsl);

		Source xmlSource = new StreamSource(fileXMLOrigen);
		Source xsltSource = new StreamSource(fileXSLOrigen);

		StringWriter cadenaSalida = new StringWriter();

		Result bufferResultado = new StreamResult(cadenaSalida);

		TransformerFactory factoriaTrans = TransformerFactory.newInstance();
		Transformer transformador = factoriaTrans.newTransformer(xsltSource);

		transformador.transform(xmlSource, bufferResultado);

		String res=cadenaSalida.toString();
		return res;
	}

	private File creaFile(String xml) {
		File fileXMLOrigen = new File(getServletContext().getRealPath(xml));
		return fileXMLOrigen;
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
